import urllib.request
import urllib.parse

# 获取get请求
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode('utf-8'))

# 获取post请求
data = bytes(urllib.parse.urlencode({"hello":"world"}), encoding = "utf-8")
try:
	response = urllib.request.urlopen("http://httpbin.org/post", data = data, timeout = 5)
	print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
	print("time out")

# 爬取豆瓣
url = "https://www.douban.com"
headers = {
	"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
}
data = bytes(urllib.parse.urlencode({"hello":"world"}), encoding = "utf-8")
request =urllib.request.Request(url = url, data = data, headers = headers, method = "POST")
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))